import { useState } from 'react';

class ModalStateType {
  visible: { [key: string]: any };
  title: { [key: string]: any };
  name: string;
  currentType: string | null;
  constructor() {
    this.visible = {};
    this.title = {};
    this.name = '';
    this.currentType = null;
  }
}

interface ParamsType {
  type: string;
  name?: string;
  title?: string | React.ReactNode;
}

function useCommonModal() {
  const [modelState, setModelState] = useState<ModalStateType>(new ModalStateType());
  //取消弹框
  const cancelModal = (type?: string, clear?: boolean): void => {
    let visible = { ...modelState.visible };
    const currentType = modelState.currentType;
    if (type) {
      delete visible[type];
    } else if (clear) {
      visible = {};
    } else if (currentType) {
      delete visible[currentType];
    }

    //更新数据
    setModelState({
      ...modelState,
      visible,
      currentType: type || currentType,
    });
  };
  //显示弹框
  const showModal = (payload: ParamsType | string) => {
    const visible = { ...modelState.visible };
    const title = { ...modelState.title };
    const type = typeof payload === 'object' ? payload.type : payload;
    const name = (typeof payload === 'object' && payload.name) || '';

    if (typeof payload === 'object' && payload.title) {
      title[type] = payload.title;
    }

    if (type) {
      let keys = Object.keys(visible);
      if (!keys.includes(type)) {
        visible[type] = true;
        //更新数据
        setModelState({
          ...modelState,
          name: name,
          title,
          visible,
          currentType: type,
        });
      }
    }
  };

  return {
    ...modelState,
    setModelState,
    showModal,
    cancelModal,
  };
}
export default useCommonModal;
